# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from san import models
from django.template.loader import get_template
from django.shortcuts import render
from django.template import RequestContext, loader
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from storagedata.djsan import Sanimport
import json
import threading
from san.tools import Sum2
import threading
from django.views.decorators.cache import cache_page
@login_required(login_url="/login/")
def index(request):
    messages = {}
    sanobj = models.San.objects.all()
    storobj = models.Storage.objects.all()
    hostobj = models.Host.objects.all()
    from work.models import Work
    from work.models import Fault

    workobj = Work.objects.all()
    workmessobj = Work.objects.all().order_by("-WO_time")[0:5]
    faultmessobj = Fault.objects.all().order_by("-FA_time")[0:5]
    totalstorage = 0
    for i in storobj:
        totalstorage += float(i.ST_totalrawcap)
    import time
    guihuatime = [2017,2018]
    #图表时间
    data2017 = []
    data2018 = []
    obj = Work.objects.filter(WO_fishtime__year="2017")
    for i in range(1,13):
        guihuaceshi = 0
        for k in obj:
            a = k.WO_fishtime
            if a.month == i:
                guihuaceshi += float(k.WO_CAP)
        data2017.append(guihuaceshi)
    obj = Work.objects.filter(WO_fishtime__year="2018")
    for i in range(1,13):
        guihuaceshi = 0
        for k in obj:
            a = k.WO_fishtime
            if a.month == i:
                guihuaceshi += float(k.WO_CAP)
        data2018.append(guihuaceshi)
    #老的
    #新的
    messages = {"sandata": sanobj, "stordata": storobj, "totalstorage": totalstorage,"hostdata":hostobj,"workdata":workobj,"workmessdata":workmessobj,"faultdata":faultmessobj,
                "guihuatime":guihuatime,
                # "data2017":data2017,
                "data2018":data2018,
                "data2017":data2017
                }
    return render(request,"index.html",messages)
@login_required(login_url="/login/")
def log(request):
    messages = {"data":"","status":"1"}
    if request.method == "GET" and request.GET != {}:
        try:
            mess = request.GET["mess"]
            mess = mess.strip()
            a = request.GET["a"]
        except Exception as e:
            mess = ""
            a = ""
        if mess == "":
            data = models.Doment.objects.all().order_by("-dotime")
        else:
            if a == "w":
                try:
                    a = models.San.objects.filter(sn = mess).first()
                    if not a:
                        a = models.Storage.objects.filter(ST_sn=mess).first()
                        data = models.Doment.objects.filter(storage=a.id).order_by("-dotime")
                    else:
                        data = models.Doment.objects.filter(san=a.id).order_by("-dotime")
                except Exception as e:
                    data = ""
            if a == "i":
                try:
                    a = models.San.objects.filter(prodect = mess).first()
                    if not a:
                        a = models.Storage.objects.filter(ST_prodect=mess).first()
                        data = models.Doment.objects.filter(storage=a.id).order_by("-dotime")
                    else:
                        data = models.Doment.objects.filter(san=a.id).order_by("-dotime")
                except Exception as e:
                    data = ""
            if a == "s":
                try:
                    a = models.San.objects.filter(ip = mess).first()
                    if not a:
                        a = models.Storage.objects.filter(ST_ip=mess).first()
                        data = models.Doment.objects.filter(storage=a.id).order_by("-dotime")
                    else:
                        data = models.Doment.objects.filter(san=a.id).order_by("-dotime")
                except Exception as e:
                    data = ""
    else:
        try:
            data = models.Doment.objects.all().order_by("-dotime")
        except Exception as e:
            messages["status"] = 0
    if not request.GET.get("page"):
        page = 1
    else:
        page = request.GET.get("page")
    paginator = Paginator(data, 10)
    contacts = paginator.page(page)
    context = {"contacts":contacts}
    return render(request,"log.html",context)
@login_required(login_url="/login/")
def log_xiangxi(request,log_id):
    try:
        data = models.Doment.objects.filter(id=log_id)
    except Exception as e:
        data = ""
    context = {'data': data}
    # print(data[0].san.ip)
    return render(request, 'log_xijie.html', context)

from san.sanportimport import sanportinport
@login_required(login_url="/login/")
def logupdate(request,update_id):
    ret = sanportinport(update_id)
    return HttpResponse(ret)
@login_required(login_url="/login/")
def Sanlink(request):
    mess = {"status":"","data":"","err":""}
    try:
        obj = models.San.objects.all()
    except Exception as e:
        mess["err"] = e
        data = ""
    mess["data"] = obj
    return render(request, "san.html",mess)
@login_required(login_url="/login/")
def Storges(request):
    stobj = models.Storage.objects.all()
    return render(request, "storage.html",{"data":stobj})
@login_required(login_url="/login/")
def Alert(request):
    return render(request, "alert.html", locals())
from san.sanbokescript import sanportdata,sanportsum
@login_required(login_url="/login/")
def Sanupdateall(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        try:
            sanobj = models.San.objects.filter(prodname="Brocade")
            for i in sanobj:
                a = models.Doment.objects.filter(san_id=i.id).order_by("-dotime").first()
                if a:
                    t1 = threading.Thread(target=sanportdata,args=(i.id,a.text,))
                    t2 = threading.Thread(target=sanportsum,args=(i.id,))
                    t1.start()
                    t2.start()
                    # sanportdata(i.id,a.text)
                    # sanportsum(i.id)
            sanobj = models.San.objects.filter(prodname="CISCO")
            for i in sanobj:
                a = models.Doment.objects.filter(san_id=i.id).order_by("-dotime").first()
                if a:
                    from san.ciscoscript import Cisco_to_data
                    t1 = threading.Thread(target=Cisco_to_data,args=(i.id,a.text,))
                    t1.start()
        except Exception as e:
            ret["status"] = False
            ret["error"] = "未知错误"
    # print(ret)
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Sanmess(request,sanmess_id):
    sanportobj = models.Sanport.objects.values("id","index","slot","port","speed","type","wwn__wwn","crc_err","TX_Power","RX_Power","rx","tx","wwn__host_wwn__ip","wwn__storage_wwn__ST_ip","wwn__host_wwn__app").filter(san_id = sanmess_id).order_by("slot","port")
    # Wwn = []
    # for i in sanportobj:
    #     wwn = models.Wwn.objects.filter(Sanport_wwn_id = i.id)
    #     if len(wwn) >0:
    #         Wwn.append((wwn[0].wwn))
    #     else:
    #         Wwn.append(" ")
    # print(Wwn)
    sanname = models.San.objects.get(id = sanmess_id)
    if sanname.prodname == "Brocade":
        return render(request,"san_brocade.html",{"data":sanportobj})
    elif sanname.prodname == "CISCO":
        return render(request, "san_cisco.html", {"data": sanportobj})
@login_required(login_url="/login/")
def Sancompall(request):
    mess = {"status": "", "data": "", "error": ""}
    data =[]
    sanobj = models.San.objects.filter(
        Q(prodname="Brocade") | Q(prodname="惠普"))
    for k in sanobj:
        obj = models.Doment.objects.filter(san_id=k.id).order_by("-dotime")
        if obj:
            new = Sanimport(obj[0].text)
            newdata = new.Sfpshow()
            newhardware = new.Hardware()
            # print(k.ip)
            # print(newhardware)
            old = Sanimport(obj[1].text)
            oldhardware = old.Hardware()
            # print(oldhardware)

            olddata = old.Sfpshow()
            for i in newdata:
                if newdata[i]["speed"] != olddata[i]["speed"]:
                    data.append("%s:时间：%s----->时间：%s  端口：%s-状态由 %s 变更为 %s" % (
                        k.ip, obj[1].dotime, obj[0].dotime, i, olddata[i]["speed"], newdata[i]["speed"]))
                if newdata[i]["wwn"] != olddata[i]["wwn"]:
                    data.append("%s:时间：%s ----->时间：%s  端口：%s - wwn由 %s变更为 %s" % (
                        k.ip, obj[1].dotime, obj[0].dotime,i, olddata[i]["wwn"], newdata[i]["wwn"]))
                if newdata[i]["crc_err"] != olddata[i]["crc_err"]:
                    data.append("%s:时间：%s----->时间：%s  端口：%s-数据帧由 %s 变更为 %s" % (
                        k.ip, obj[1].dotime, obj[0].dotime,i, olddata[i]["crc_err"], newdata[i]["crc_err"]))
                if newdata[i]["enc_out"] != olddata[i]["enc_out"]:
                    data.append("%s:时间：%s----->时间：%s  端口：%s-光纤输出报错由 %s 变更为 %s " % (
                        k.ip, obj[1].dotime, obj[0].dotime, i, olddata[i]["enc_out"], newdata[i]["enc_out"]))
            if newhardware != oldhardware:
                data.append("%s硬件出现问题，请排查" %(k.ip))
        mess["data"] = data
    return  render(request,"error.html",mess)
# @cache_page(60 * 15)
@login_required(login_url="/login/")
def Host(request):
    return render(request,"host.html")
@login_required(login_url="/login/")
def Addhost(request):
    return render(request,"addhost.html")
@login_required(login_url="/login/")
def addhost_ajax(request):
    ret = {"status":True,"error":None,"data":None}
    if request.method == "POST":
        mess = json.loads(request.POST.get("data"))
        for i in mess:
            if  mess[i]["ip"] == "" or mess[i]["wwn"] == "":
                ret["status"] = False
                ret["error"] = "主机IP或者wwn不能为空"
                # print(ret)
                break
            try:
                host_data = {
                    "prodname": mess[i]["prodname"],
                    "ip": mess[i]["ip"],
                    "hostname": mess[i]["hostname"],
                    "app": mess[i]["app"],
                    "apptype": mess[i]["apptype"],
                    "prodect": mess[i]["prodect"],
                    "sn": mess[i]["sn"],
                    "position": mess[i]["position"],
                }
                try:
                    obj_host = models.Host.objects.get(sn = mess[i]["sn"],ip=mess[i]["ip"])
                    obj_host.prodname = mess[i]["prodname"]
                    obj_host.hostname = mess[i]["hostname"]
                    obj_host.app = mess[i]["app"]
                    obj_host.apptype = mess[i]["apptype"]
                    obj_host.prodect = mess[i]["prodect"]
                    obj_host.position = mess[i]["position"]
                    obj_host.save()
                except Exception as e:
                    print(e)
                    obj_host = models.Host.objects.create(**host_data)
            except Exception as e:
                ret["error"] = e
                ret["status"] = False
                obj_host.delete()
                break
            wwn_list = list(set(mess[i]["wwn"].split(" ")))
            while "" in wwn_list:
                wwn_list.remove("")
            for w in wwn_list:
                from scriptd.towwn import WWn
                wwn = WWn(w)
                if wwn != False:
                    # print(wwn)
                    wwndata = {
                        "wwn":wwn,
                        "host_wwn_id":obj_host.id,
                    }
                    try:
                        objwwn = models.Wwn.objects.filter(wwn = wwn)
                        if objwwn:
                            objwwn[0].host_wwn = obj_host
                            objwwn[0].save()
                        else:
                            models.Wwn.objects.create(**wwndata)
                    except Exception as e:
                        obj_host.delete()
                        ret["error"] = "wwn到数据库错误%s"%(e)
                        # print(ret["error"])
                        ret["status"] = False
                        break
                else:
                    obj_host.delete()
                    ret["error"] = "wwn输入错误"
                    ret["status"] = False
                    break
    return HttpResponse(json.dumps(ret))

@login_required(login_url="/login/")
def Storagemess(request,storage_id):
    ret = {"status":True,"error":None,"data":None}
    obj = models.Storage.objects.get(id = storage_id)
    ret["data"]= obj
    # print(obj.hostgroup_set.all())
    return render(request,"storagemess.html",ret)
@login_required(login_url="/login/")
def Storages_log(request):
    st_log = models.Doment.objects.values("id","dotime","storage__ST_sn","storage__ST_ip","storage__ST_prodname","storage__ST_prodect").filter(
        Q(storage__ST_prodname="富士通") | Q(storage__ST_prodname="日立") | Q(storage__ST_prodname="华为") | Q(
            storage__ST_prodname="EMC"))
    ret = {"data":st_log,"little":"存储"}
    return render(request,"log_storage.html",ret)
@login_required(login_url="/login/")
def San_log(request):
    st_log = models.Doment.objects.values("id","dotime","san__prodname","san__prodect","san__sn","san__ip").filter(
        Q(san__prodname="Brocade") | Q(san__prodname="CISCO")).order_by("-dotime")
    ret = {"data":st_log,"little":"光交"}
    return render(request,"log.html",ret)
    # ret = {"status": True, "error": None, "data": None}
    # if request.method == "POST":
    #     # id = request.POST.get("data")
    #     iddict = request.POST
    #     id = iddict["id"]
    #     objst = models.Storage.objects.filter(id = id).first()
    #     st_log = models.Doment.objects.filter(storage_id=objst.id).order_by("-dotime").first()
    #     if objst.ST_prodname == "富士通":
    #         if st_log:
    #             Fsttodata(objst,st_log.text)
    #         else:
    #             ret["status"] = False
    #             ret["error"] = "该存储没有日志"
    #     elif objst.ST_prodname == "日立":
    #         if st_log:
    #             hitachi_to_data(id,st_log.text)
    #         else:
    #             ret["status"] = False
    #             ret["error"] = "该存储没有日志"
    # print(ret)
    # return HttpResponse(json.dumps(ret))

from django.contrib.auth import logout
from django.http import HttpResponseRedirect
from django.contrib import auth
def Logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/")
@login_required(login_url="login/")
def San_sel_update_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        # id = request.POST.get("data")
        iddict = request.POST
        id = iddict["id"]
        try:
            sanobj = models.San.objects.get(id=id)
            if sanobj.prodname == "Brocade":
                a = models.Doment.objects.filter(san_id=sanobj.id).order_by("-dotime").first()
                if a:
                    t1 = threading.Thread(target=sanportdata,args=(id,a.text,))
                    t1.start()
                    sanportsum(id)
            if sanobj.prodname == "CISCO":
                a = models.Doment.objects.filter(san_id=sanobj.id).order_by("-dotime").first()
                if a:
                    from san.ciscoscript import Cisco_to_data
                    # Cisco_to_data(id,a.text)
                    t2 = threading.Thread(target=Cisco_to_data,args=(id,a.text,))
                    t2.start()
                else:
                    ret["status"] = False
                    ret["error"] = "开发中"
        except Exception as e:
            ret["status"] = False
            ret["error"] = "未知错误%s"%(e)
    return HttpResponse(json.dumps(ret))
from work.models import Work
@login_required(login_url="/login/")
def Search_messages(request):
    ret = {"status": True, "error": None, "data": None,"wwn":None,"host":None}
    if request.method == "GET" and request.GET != {}:
        try:
            mess = request.GET["mess"]
            mess = mess.strip()
            select = request.GET["select"]
        except Exception as e:
            print(e)
        if mess == "":
            ret["status"] = "输入不能为空"
        else:
            if select == "i":
                host = models.Host.objects.filter(ip__icontains =mess)
                ret["host"] = host
                wwn = []
                for i in host:
                    for w in  i.wwn_set.all():
                        wwn.append(w)
                ret["wwn"] = wwn
                sthost = []
                stport = []
                for n in wwn:
                    for nn in n.SThost.all():
                        sthost.append(nn)
                ret["sthost"] = sthost
                ret["stport"] = stport
                ret["status"] = "未找到信息，或者输入错误"
            elif select == "w":
                from scriptd.towwn import WWn
                try:
                    wwn = WWn(mess)
                    obj = models.Wwn.objects.filter(wwn = wwn)
                    # print(obj)
                    # print(obj[0].host_wwn)
                    try:
                        ret["host"] = objhost = models.Host.objects.filter(ip__icontains=obj[0].host_wwn.ip)
                        ret["wwn"] = a = objhost[0].wwn_set.all()
                        # print(a)
                    except Exception as e:
                        ret["status"] = "主机信息无"
                        ret["wwn"] = obj
                        ret["host"] =""
                except Exception as e:
                    ret["status"] = "wwn输入错误，需要全部输入，可不用输入：，大小写均可输入"
                    ret["wwn"] = ""
                    ret["host"] = ""
            elif select == "s":
                pass
                # print(ret)
    return render(request, "search.html", ret)
def Auto_login(request):
    # from django.contrib.auth import authenticate, login
    ret = {"status": True, "error": "", "data": ""}
    if request.user.is_authenticated:
        return HttpResponseRedirect("/")
    else:
        return render(request, "login.html",ret)

from django.contrib.auth import authenticate, login
def Login_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.user.is_authenticated:
        return HttpResponseRedirect("/")
    else:
        if request.method == "POST":
            username = request.POST.get("user")
            password = request.POST.get("password")
            if request.user.is_authenticated:
                return HttpResponseRedirect("/")
            else:
                if username == "" or password == "":
                    ret["status"] = False
                    ret["error"] = "用户名或者密码不能为空"
                    return HttpResponse(json.dumps(ret))
                else:
                    user = authenticate(username=username, password=password)
                    if user is not None:
                        login(request, user)
                        return HttpResponse(json.dumps(ret))
                    else:
                        ret["status"] = False
                        ret["error"] = "用户名或者密码错误"
                        return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Caiji(request):
    obj = models.San.objects.all()
    return render(request,"caiji.html",{"data":obj})
@login_required(login_url="/login/")
def Caiji_san_port(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        sanid = request.POST.get("id")
        obj = models.San.objects.get(id = sanid)
        portxinxi = models.Sanport.objects.filter(san_id = obj)
        slot = []
        port = []
        for i in portxinxi:
            slot.append("<option>%s</option>"%(i.slot))
            port.append("<option>%s</option>"%(i.port))
        slot = list(set(slot))
        port = list(set(port))
        ret["slot"] = slot
        ret["port"] = port
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def San_port_tables(request):
    return render(request, "porttables.html")
@login_required(login_url="/login/")
def Yewu(request):
    obj = models.Storage.objects.values("stmap__app","ST_prodect","ST_sn","ST_totalcap","ST_usecap","stmap__mapname","stmap__totalcap").all()
    return render(request,"yewu.html",{"data":obj})
# from san.brocade_caiji import Borde_huitu
@login_required(login_url="/login/")
def San_huitu_update(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "GET":
        from san.brocade_caiji import bokestart
        t1 = threading.Thread(target=bokestart)
        t1.start()
        # sanobj = models.San.objects.filter(prodname="Brocade")
        # for i in sanobj:
        #     try:
        #         Borde_huitu(i.id)
        #     except Exception as e:
        #         ret["error"] = i.id,e
    return HttpResponse(json.dumps(ret))
#返回字符串形式 2017-4-5 13:45:45
def Timezhuanhuan(time):
    return str(time.year) + "-" + str(time.month)+ "-" + str(time.day) + " " + str(time.hour) + ":" + str(time.minute) + ":" + str(time.second)

@login_required(login_url="/login/")
def San_port_err_tables(request):
    ret = {"status": True, "error": None, "data": None}
    obj = models.San.objects.filter(prodname = "Brocade")
    ret["data"] = obj
    return render(request,"port_err_tables.html",ret)

@login_required(login_url="/login/")
def San_err_get_shuju(request):
    ret = {"status": True, "error": None, "data": None}
    try:
        if request.method == "GET":
            sanid = request.GET["sanid"]
            slot = request.GET["slot"]
            port = request.GET["port"]
            if slot == "None":
                obj = models.Sanport.objects.filter(san_id=int(sanid),port=int(port)).first()
            else:
                obj = models.Sanport.objects.filter(san_id=int(sanid), slot=int(slot), port=int(port)).first()
            if obj:
                pass
                cleandata = models.Sanlog_clean.objects.filter(San_portid_id=obj.id).order_by("log_time")
                time = []
                name = ["linkfail","enc_in","crc_err","loss_sig","enc_out","loss_sync"]
                linkfail = []
                Enc_in = []
                crc_err = []
                enc_out = []
                Loss_sync = []
                Loss_sig = []
                html = ""
                for i in cleandata:
                    linkfail.append(i.link_fail)
                    time.append(Timezhuanhuan(i.log_time))
                    Enc_in.append(Sum2(i.enc_in))
                    crc_err.append(Sum2(i.crc_err))
                    Loss_sig.append(Sum2(i.loss_sig))
                    enc_out.append(Sum2(i.enc_out))
                    Loss_sync.append(Sum2(i.loss_sync))
                    html += "<tr>" + \
                            "<td>" + str(i.San_wwn) + "</td>" + \
                            "<td>" + str(i.enc_in) + "</td>" + \
                            "<td>" + str(i.crc_err) + "</td>" + \
                            "<td>" + str(i.crc_g_eof) + "</td>" + \
                            "<td>" + str(i.two_shrt) + "</td>" + \
                            "<td>" + str(i.two_long) + "</td>" + \
                            "<td>" + str(i.bad_eof) + "</td>" + \
                            "<td>" + str(i.enc_out) + "</td>" + \
                            "<td>" + str(i.disc_c3) + "</td>" + \
                            "<td>" + str(i.link_fail) + "</td>" + \
                            "<td>" + str(i.loss_sync) + "</td>" + \
                            "<td>" + str(i.loss_sig) + "</td>" + \
                            "<td>" + str(i.frjt) + "</td>" + \
                            "<td>" + str(i.fbsy) + "</td>" + \
                            "<td>" + str(i.timeout_tx) + "</td>" + \
                            "<td>" + str(i.timeout_rx) + "</td>" + \
                            "<td>" + str(i.RX_Power) + "</td>" + \
                            "<td>" + str(i.TX_Power) + "</td>" + \
                            "<td>" + str(i.log_time) + "</td>" + \
                            "</tr>"
        ret["html"] = html
        ret["linkfail"] = linkfail
        ret["get_time"] = time
        ret["name"] = name
        ret["enc_in"] = Enc_in
        ret["crc_err"] = crc_err
        ret["loss_sig"] = Loss_sig
        ret["enc_out"] = enc_out
        ret["loss_sync"] = Loss_sync

    except Exception as e:
        ret["status"] = False
        ret["error"] = str("not data" + str(e))
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def san_liuliang_import(request):
    san = models.San.objects.filter(prodname = 'Brocade')
    return render(request,"san_liuliang_import.html",{"data":san})
from san.san_liuliang_import import Liuliang,liuliang_mini
@login_required(login_url="/login/")
def san_liuliang_im(request):
    ret = {"status": True, "error": None, "data": None}
    try:
        if request.method == "POST":
            sanid = request.POST.get("id")
            text = request.POST.get("text")
            obj = models.Sanport.objects.filter(san_id=sanid)
            num = models.Sanport.objects.filter(san_id=sanid).count()
            if int(num) > 100:
                datashuju = (Liuliang(text))
                if datashuju:
                    for i in obj:
                        i.rx = datashuju[int(i.slot)][int(i.port)]
                        i.save()
                else:
                    ret["status"] = False
                    ret["error"] = "信息错误"
            elif int(num) > 23 and int(num) < 100:
                datashuju = liuliang_mini(text)
                if datashuju:
                    for i in obj:
                        i.rx = datashuju[int(i.port)]
                        i.save()
                else:
                    ret["status"] = False
                    ret["error"] = "信息错误"
            else:
                ret["status"] = False
                ret["error"] = "错误的信息，或者功能未开发"
    except Exception as e:
        ret["status"] = False
        ret["error"] = e
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Hot_wwn(request):
    obj = models.Sanport.objects.values("id", "san__prodect", "san__ip", "wwn__host_wwn", "wwn__host_wwn__app",
                                         "wwn__host_wwn__ip", "wwn__storage_wwn__ST_prodect","wwn__wwn",
                                         "wwn__storage_wwn__ST_ip","rx","tx").filter(rx__contains= "m")
    from django.db.models import Q
    con = Q()
    q1 = Q()
    q1.connector = 'OR'
    q1.children.append(('rx__gt', 5))
    q1.children.append(('tx__gt', 5))
    q2 = Q()
    q2.connector = 'and'
    q2.children.append(('san__prodname', "CISCO"))
    con.add(q1, 'AND')
    con.add(q2, 'AND')
    # obj2 = models.Sanport.objects.filter(con)
    obj2 = models.Sanport.objects.values("id", "san__prodect", "san__ip", "wwn__host_wwn", "wwn__host_wwn__app",
                                         "wwn__host_wwn__ip", "wwn__storage_wwn__ST_prodect","wwn__wwn",
                                         "wwn__storage_wwn__ST_ip","rx","tx").filter(con)
    return render(request,"host_wwn.html",{"data":obj,"data2":obj2})

def host_search_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        sea = request.POST.get("id")
        text = request.POST.get("text")
        if text == "":
            obj = models.Host.objects.all()
        else:
            if sea == "s":
                print("s")
            elif sea == "q":
                q1 = Q()
                q1.connector = 'OR'
                q1.children.append(('hostname__icontains', text))
                q1.children.append(('app__icontains', text))
                q1.children.append(('apptype__icontains', text))
                q1.children.append(('ip__icontains', text))
                q1.children.append(('prodect__icontains', text))
                obj = models.Host.objects.filter(q1)
    html = ""
    for i in obj:
        wwn = ""
        for k in i.wwn_set.all():
            if k.Sanport_wwn:
                wwn += """<nobr style = "color:red">""" + str(k.wwn) + "-" + str(k.Sanport_wwn.san) + " " + "</nobr>"
            else:
                wwn += str(k.wwn)
        html += "<tr>" + \
                "<td>" + str(i.id) + "</td>" + \
                "<td>" + str(i.prodname) + "</td>" + \
                "<td>" + str(i.prodect) + "</td>" + \
                "<td>" + str(i.sn) + "</td>" + \
                "<td>" + str(i.ip) + "</td>" + \
                "<td>" + str(i.hostname) + "</td>" + \
                "<td>" + str(i.app) + "</td>" + \
                "<td>" + str(i.apptype) + "</td>" + \
                "<td>" + wwn + "</td>" + \
                "</tr>"
    ret["data"] = html
    return HttpResponse(json.dumps(ret))